<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ersv
 * Date: 12/13/12
 * Time: 10:41 AM
 * To change this template use File | Settings | File Templates.
 */
class Router_EMyLink
{
    public $application;
    public $module;
    public $action;
    public $request;
    /*
     * lấy tất cả router trong file routing.ini để kiểm tra xem url có thích hợp trong ruoter ko
     */
    public function checkURL($url)
    {
        if(file_exists(ROOT_PATH."/config/routing.ini"))
        {
            $router=parse_ini_file("/config/routing.ini");
            if(isset($router["router"]))
            {
                $arr_router=$router["router"];
                foreach($arr_router as $value)
                {
                    $out=$this->check($this->cutRouter($router[$value]),$url);
                    if($out)
                    {
                        $arr_type = $router[$value."_parameter_type"];
                        $arr_name = $router[$value."_parameter_name"];
                        for($i=1;$i<count($out)-1;$i++)
                        {
                             eval("$"."this->request[$"."arr_name[$"."i-1]] = (".$arr_type[$i-1].")$"."out[$"."i];");
                        }
                        $application_module_action=explode("_",$value);
                        $this->application=$application_module_action[0];
                        $this->module=$application_module_action[1];
                        $this->action=$application_module_action[2];
                        return true;
                    }
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    protected function cutRouter($router)
    {
        $arr=array();
        if(preg_match('/.*?/',$router))
        {
            $arr=explode(".*?",$router);
        }
        else
        {
            $arr[]=$router;
        }
        return $arr;
    }
    protected function check($arr,$url)
    {
        $str="";
        $first=true;
        $last="";
        foreach($arr as $value)
        {
            if($first)
            {
                $arr_check_first=explode($value,$url);
                if($arr_check_first[0] !='/')
                {
                    return false;
                }
                $first=false;
            }
            if(!preg_match('/'.$value.'/',$url))
            {
                return false;
            }
            else
            {
                $str.=$value."(.*)";
                $last=$value;
            }
        }
        $arr_check_first=explode($last,$url);
        if($arr_check_first[1] !='')
        {
            return false;
        }
        preg_match('/'.$str.'/',$url,$out);
        return $out;
    }
}
